package com.chrilwe.pigpig.filesystem.controller;

import java.io.FileNotFoundException;
import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.chrilwe.pigpig.filesystem.common.ResultEnum;
import com.chrilwe.pigpig.filesystem.common.request.PreUploadRequest;
import com.chrilwe.pigpig.filesystem.common.response.PreUploadResult;
import com.chrilwe.pigpig.filesystem.common.response.UploadChunkResult;
import com.chrilwe.pigpig.filesystem.service.FileUploadService;

/**
 * 大文件管理
 * 
 * @author chrilwe
 * @date 2020-10-7
 */
@RestController
@RequestMapping("/filesystem/bigfile")
public class BigfileController {

	@Autowired
	private FileUploadService fileUploadService;

	// 预上传
	@GetMapping("/preUpload")
	public PreUploadResult preUpload(@RequestParam("preUploadRequest") PreUploadRequest preUploadRequest) {
		PreUploadResult preUpload = null;
		try {
			preUpload = fileUploadService.preUpload(preUploadRequest);
		} catch (IOException e) {
			return new PreUploadResult(ResultEnum.UNKNOW_ERR.getCode(), ResultEnum.UNKNOW_ERR.getName(), 0, 0);
		}
		return preUpload;
	}

	@PostMapping("/uploadChunk/${fileMd5}/${chunkName}")
	public UploadChunkResult uploadChunkFile(@RequestBody MultipartFile chunk,
			@PathVariable("chunkName") String chunkName, @PathVariable("fileMd5")String fileMd5) {
		UploadChunkResult uploadChunk = null;
		try {
			uploadChunk = fileUploadService.uploadChunk(chunk, fileMd5, chunkName);
			return uploadChunk;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return uploadChunk = new UploadChunkResult(ResultEnum.UNKNOW_ERR.getCode(), ResultEnum.UNKNOW_ERR.getName());
	}
}
